<template>
  <div class="filter-list">
    <div v-for="(item, index) in filterList" :key="index" class="filter-item">
      <div class="one-cell">
        <!-- 选择字段 -->
        <el-select v-if="fieldChidrenList" v-model="item.field" filterable clearable class="width120 mr10" popper-class="global-select-down" size="small" name="filterField" @change="changeField(item, index)">
          <el-option
            v-for="opt in fieldChidrenList || []"
            :key="opt[keyName]"
            :label="getLabelName(opt)"
            :value="opt[keyName]" />
        </el-select>
        <!-- 选择运算符：如果是时间筛选则不展示运算符-->
        <el-select v-if="!isTimeField(item)" v-model="item.operation" popper-class="global-select-down" size="small" class="width80 mr10" name="filterField">
          <template v-for="opt in mathOptions">
            <el-option
              v-if="!(isNumberField(item) && (opt === '包含' || opt === '不包含'))"
              :key="opt"
              :label="opt"
              :value="opt" />
          </template>
        </el-select>
        <!-- 根据不同的字段类型选择内容 -->
        <selectSystemField
          :item="item"
          :system-condition-options="{mathOptions: mathOptions}"
          :time-range-type-options="timeRangeTypeOptions"
          :link-children="true"
          class="mr10"
          @timeRangeTypeChange="timeRangeTypeChange"
          @timeChange="timeChange"
          @sendData="changeData" />
        <!-- 筛选按钮，系统筛选才有 -->
        <div v-if="isFilter && item.field" :class="{'active': item.isOpenFilter}" class="filter-icon-btn icon-container" @click="switchFilter(item, index)">
          <img v-if="!item.isOpenFilter" :src="openFilterIcon" style="width: 16px;" alt="">
          <img v-else :src="openFilterActiveIcon" style="width: 16px;" alt="">
        </div>
        <div v-if="filterList.length > 1" class="delete-btn icon-container" @click="deleteItem(index)"><img :src="deleteFilterIcon" style="width: 12px;" alt=""></div>
        <div v-if="index === 0" class="button-text icon-container" @click="addItem"><img :src="addFilterIcon" style="width: 18px;" alt=""></div>
      </div>
      <!-- 筛选 -->
      <div v-if="isFilter && item.isOpenFilter && item.top !== 0" class="default-filter-value">
        <div class="label"><span class="dot"/>默认筛选条件：</div>
        <!-- 根据不同的字段类型选择内容 -->
        <selectSystemField
          :item="item"
          :time-range-type-options="timeRangeTypeOptions"
          :system-condition-options="{mathOptions: mathOptions}"
          :link-children="true"
          mode="default"
          @timeRangeTypeChange="timeRangeTypeChange"
          @timeChange="timeChange"
          @syncGroupDefault="syncGroupDefault($event, index)"
          @sendData="changeData" />
      </div>
      <!-- 同比和环比 -->
      <div v-if="isTimeField(item) && item.top !== 0 && isContrast && (item.timeRangeType || (item.isOpenFilter && item.defaultMath)) && contrastSelectShow(item, index)" class="time-month-year">
        <el-checkbox v-model="item.monthOnMonth">
          <span class="contrast-title">环比</span>
          <span class="contrast-content">{{ contentFilter(item.timeRangeType || item.defaultMath).month }}</span>
        </el-checkbox>
        <el-checkbox
          v-if="(item.timeRangeType && item.timeRangeType !== 'year' && item.timeRangeType !== 'week'&& item.timeRangeType !== 'lastweek'&& item.timeRangeType !== 'lastyear') ||
          (!item.timeRangeType && item.defaultMath !== 'year' && item.defaultMath !== 'week'&& item.defaultMath !== 'lastweek'&& item.defaultMath !== 'lastyear')"
          v-model="item.yearOnYear">
          <span class="contrast-title">同比</span>
          <span class="contrast-content">{{ contentFilter(item.timeRangeType || item.defaultMath).year }}</span>
        </el-checkbox>
        <el-checkbox
          v-if="(item.timeRangeType && (['week','month','year'].includes(item.timeRangeType) || ['week','month','year'].includes(item.defaultMath)))"
          v-model="item.sameTimeCompare">
          <div class="flex-center">仅对比同期数据<tipIcon content="勾选后将按照日进行数据对比" class="ml4" style="top: 1px"/></div>
        </el-checkbox>
      </div>
    </div>
  </div>
</template>

<script>
import toolMixin from '@/components/ReportManage/dataFilter/mixins/toolMethods';
// components
import selectSystemField from './dataFilter/selectSystemField';
// img
import addFilterIcon from '@/assets/reportManage/add-filter.png';
import deleteFilterIcon from '@/assets/reportManage/delete-filter.png';
import openFilterIcon from '@/assets/reportManage/open-filter.png';
import openFilterActiveIcon from '@/assets/reportManage/open-filter-active.png';

export default {
  components: { selectSystemField },
  mixins: [toolMixin],
  model: {
    prop: 'filterList',
    event: 'changeData'
  },
  props: {
    filterList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    fieldChidrenList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    mathOptions: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isContrast: {
      type: Boolean,
      default: false
    },
    isFilter: {
      type: Boolean,
      default: true
    },
    keyName: {
      type: String,
      default: 'name'
    },
    unitParams: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      addFilterIcon, deleteFilterIcon, openFilterActiveIcon, openFilterIcon,
      timeRangeTypeOptions: [
        { id: '', name: '等于' },
        { id: 'day', name: '今日' },
        { id: 'yesterday', name: '昨日' },
        { id: 'week', name: '本周' },
        { id: 'lastweek', name: '上周' },
        { id: 'month', name: '本月' },
        { id: 'lastmonth', name: '上月' },
        { id: 'year', name: '本年' },
        { id: 'lastyear', name: '去年' }
      ]
    };
  },
  watch: {
    isContrast: function(newV, oldV) {
      if (!newV && this.filterList.length > 0) {
        this.filterList.forEach(i => {
          i.monthOnMonth = false;
          i.yearOnYear = false;
          i.sameTimeCompare = false;
        });
      }
    },
    filterList: {
      handler(val) {
        if (val.length === 0) {
          val.push({
            top: '', // 0：报表 1：系统
            timerange: [],
            numberRange: [],
            timeRangeType: '',
            monthOnMonth: false,
            yearOnYear: false,
            sameTimeCompare: false,
            type: '', // 0:时间筛选 1:条件筛选 2:文本筛选
            begin: '',
            end: '',
            field: '',
            operation: '', // 操作，=,>,<,>=,<= 和 包含，不包含，首字
            value: '',
            conditionValue: '',
            reportField: '', // 【v2.8.9】报表字段（手动输入）,当选择的字段为报表字段时才生效
            isOpenFilter: false, // 是否开启筛选
            defaultMath: '', // 默认筛选的运算条件
            defaultValue: '', // 默认筛选条件
            defaultNumberRange: [], // 默认筛选条件
            defaultTimeRange: [] // 默认筛选条件
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * change 事件
     */
    switchFilter(item, systemIndex) {
      item.isOpenFilter = !item.isOpenFilter;
      this.timeRangeTypeChange(item);
      this.syncGroupDefault(item, systemIndex);
    },
    // 同步筛选组
    syncGroupDefault(item, systemIndex) {
      this.$emit('syncGroup', { filterItem: item, systemIndex, syncField: ['isOpenFilter', 'defaultMath'] });
    },
    // 系统字段改变
    changeField(item, index) {
      this.initDefaultData(item);
      item.operation = '';
      const curentField = this.fieldChidrenList.find(i => {
        return i[this.keyName] === item.field;
      });
      if (curentField) {
        this.$set(item, 'optionsType', curentField.optionsType);
        this.$set(item, 'top', curentField.sourceId);
        this.$set(item, 'fieldKey', curentField.fieldKey);
      } else {
        this.$set(item, 'optionsType', '');
        this.$set(item, 'top', null);
        this.$set(item, 'fieldKey', '');
      }
      // 初始化
      const isTime = this.isTimeField(item);
      if (isTime) {
        item.operation = '=';
      } else {
        item.operation = '';
      }
      item.value = '';
      item.begin = '';
      item.end = '';
      this.$set(item, 'timerange', []);
      this.$set(item, 'numberRange', []);
      this.$set(item, 'conditionValue', []);
      this.$set(item, 'yearOnYear', false);
      this.$set(item, 'monthOnMonth', false);
      this.$set(item, 'sameTimeCompare', false);
      this.$set(item, 'timeRangeType', '');

      this.$emit('syncGroup', { systemIndex: index, filterItem: item });
      this.changeData();
    },
    // 时间类型改变：day:今日 week:本周 month:本月 year:本年，yesterday:昨日 lastweek:上周 lastmonth:上月 lastyear:去年
    timeRangeTypeChange(item) {
      const isOpenFilter = item.isOpenFilter && !item.timeRangeType && item.defaultMath;
      if (item.timeRangeType !== '' || isOpenFilter) {
        item.timerange = [];
        item.begin = '';
        item.end = '';
        item.monthOnMonth = true;
        item.yearOnYear = true;
        item.sameTimeCompare = false;
      } else {
        item.monthOnMonth = false;
        item.yearOnYear = false;
        item.sameTimeCompare = false;
      }
      const isTimeRangeType = item.timeRangeType === 'year' || item.timeRangeType === 'week' || item.timeRangeType === 'lastyear' || item.timeRangeType === 'lastweek';
      const isTimeRangeTypeDefault = item.defaultMath === 'year' || item.defaultMath === 'week' || item.defaultMath === 'lastyear' || item.defaultMath === 'lastweek';
      if (isTimeRangeType || (isOpenFilter && isTimeRangeTypeDefault)) {
        item.yearOnYear = false;
      }
      this.changeData();
    },
    // 时间区间改变
    timeChange(time, item) {
      if (time && time[0]) item.begin = String(time[0]).length === 13 ? Math.floor(time[0] / 1000) : time[0];
      if (time && time[1]) item.end = String(time[1]).length === 13 ? Math.floor(time[1] / 1000) : time[1];
      if (!time) {
        item.begin = '';
        item.end = '';
      }
      this.changeData();
    },
    deleteItem(index) {
      this.filterList.splice(index, 1);
      this.changeData();
      this.$emit('syncGroup', { systemIndex: -1, deleteIndex: index });
    },
    addItem() {
      const initData = {
        top: null,
        type: 0, // 0:时间筛选 1:条件筛选 2:文本筛选
        begin: '',
        end: '',
        field: '',
        optionsType: '',
        monthOnMonth: false,
        yearOnYear: false,
        sameTimeCompare: false,
        operation: '', // 操作，=,>,<,>=,<= 和 包含，不包含，首字
        value: '',
        conditionValue: '',
        timeRangeType: '',
        reportField: '', // 【v2.8.9】报表字段（手动输入）,当选择的字段为报表字段时才生效
        isOpenFilter: false, // 是否开启筛选
        defaultMath: '', // 默认筛选的运算条件
        defaultValue: '', // 默认筛选条件
        defaultNumberRange: [], // 默认筛选条件
        defaultTimeRange: [] // 默认筛选条件
      };
      this.filterList.push(initData);
      this.changeData();

      this.$emit('syncGroup', { systemIndex: this.filterList.length - 1, filterItem: initData });
    },
    changeData() {
      this.$emit('changeData', this.filterList);
    },
    /**
     * 工具方法
     */
    // 同比环比文案
    contentFilter(type) {
      // day:今日 week:本周 month:本月 year:本年
      let contentObj = {};
      switch (type) {
        case 'yesterday':
        case 'day':
          contentObj = { month: '较前一日', year: '较上一周' };
          break;
        case 'lastweek':
        case 'week': contentObj = { month: '较前一周', year: '较上一月' }; break;
        case 'lastmonth':
        case 'month': contentObj = { month: '较前一月', year: '较上一年' }; break;
        case 'lastyear':
        case 'year': contentObj = { month: '较前一年', year: '' }; break;
      }
      return contentObj;
    },
    // 如果有多个筛选条件，只显示第一条环比/同比
    contrastSelectShow(item, index) {
      for (let i = 0; i < index; i++) {
        if (this.filterList[i] && this.filterList[i].timeRangeType && this.filterList[i].timeRangeType !== '' && this.isTimeField(this.filterList[i])) {
          item.yearOnYear = false;
          item.monthOnMonth = false;
          item.sameTimeCompare = false;
          return false;
        }
      }
      return true;
    },
    getLabelName(item) {
      const unitParams = this.unitParams;
      if (unitParams && unitParams.field && item[unitParams.field]) {
        return item.name + `（${item[unitParams.field]}）`;
      }
      return item.name;
    }
  }
};
</script>

<style lang="scss" scoped>
.one-cell {
  display: flex;
}
.width120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
.width80 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
.mr10 {
  margin-right: 10px;
}
.filter-item {
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 0;
  }
  .delete-btn {
    cursor: pointer;
    margin-right: 15px;
  }
  .icon-container {
    display: flex;
    align-items: center;
  }
}
.filter-icon-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #333333;
  margin-right: 15px;
  font-size: 14px;
  height: 32px;
  .icon {
    font-size: 16px;
  }
}
.default-filter-value {
  display: flex;
  // align-items: center;
  margin-top: 20px;
  .label {
    color: #999999;
    font-size: 14px;
    line-height: 32px;
    display: flex;
    align-items: center;
    .dot {
      width: 6px;
      height: 6px;
      background: #aeb6c7;
      border-radius: 50%;
      margin-right: 7px;
    }
  }
}
</style>
